//
//  ManagerAddressViewController.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/8/17.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved.
//

#import "ManagerAddressViewController.h"
#import "ManagerAddressTableViewCell.h"
#import "EditeAddressViewController.h"
#import "Address.h"
#import "UpdateNet.h"
#import "BLHeader.h"
#import <MBProgressHUD.h>

@interface ManagerAddressViewController () <UITableViewDelegate, UITableViewDataSource, ManagerAddressTableViewCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *addresss;
@property (nonatomic, strong) MBProgressHUD *hud;
@end

@implementation ManagerAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
}

- (void)loadData {
    [UpdateNet selectAddress:^(id resultObject, NSError *error) {
        self.addresss = resultObject;
        [self.hud hideAnimated:YES];
        [self.tableView reloadData];
    }];
}

- (void)setupUI {
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.edgesForExtendedLayout = UIEventSubtypeNone;
     self.title = @"管理地址";
    [self.tableView registerNib:[UINib nibWithNibName:@"ManagerAddressTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:ReuseIdentify];
    self.tableView.allowsSelection = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAddrNotification:) name:ADDADDRESSNOTIFICATION object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateAddressNotification:) name:UPDATEADDRESSNOTIFICATION object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deletAddrNotification:) name:DELETEADDRESSNOTIFICATION object:nil];
}


#pragma mark 更新地址通知
- (void)updateAddressNotification:(NSNotification *)notification {
    Address *newAddress = notification.object;
    for (int i = 0; i < self.addresss.count; i++) {
        Address *addr = self.addresss[i];
        if([addr.addrNo isEqualToString:newAddress.addrNo]) {
            addr.name = newAddress.name;
            addr.tel = newAddress.tel;
            addr.detail = newAddress.detail;
            addr.provice = newAddress.provice;
            addr.city = newAddress.city;
            addr.area = newAddress.area;
            addr.isApprove = newAddress.isApprove;
            if([@"是" isEqual:addr.isApprove ]) {
                for (Address *add in self.addresss) {
                    add.isApprove = @"否";
                }
                addr.isApprove = @"是";
                [self.tableView reloadData];
                return;
            }else {
                [self.tableView reloadData];
                return;
            }
        }
    }
}

#pragma mark 添加地址通知
- (void)addAddrNotification:(NSNotification *)notification {
    if(!self.addresss) {
        self.addresss = [[NSMutableArray alloc] init];
    }
    Address *address = notification.object;
    if ([address.isApprove isEqualToString:@"是"]) {
        for (Address *addr in self.addresss) {
            if (addr.isApprove) {
                addr.isApprove = @"否";
            }
        }
    }
    [self.addresss addObject:address];
    [self.tableView reloadData];
    
    
}

#pragma mark 删除地址通知
- (void)deletAddrNotification:(NSNotification *)notification {
    Address *address = notification.object;
    
    for (int i = 0; i < self.addresss.count; i++) {
        Address *addr = self.addresss[i];
        if([addr.addrNo isEqualToString:address.addrNo]) {
            [self.addresss removeObject:addr];
            if ([address.isApprove isEqualToString:@"是"]) {
                Address *addr = [self.addresss firstObject];
                addr.isApprove = @"是";
            }
            [self.tableView reloadData];
            return;
        }
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ManagerAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseIdentify];
    Address * add = [self.addresss objectAtIndex:indexPath.row];
    [cell setupCell:add];
    cell.delegate = self;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addresss.count;
}

- (IBAction)addNewAddr:(UIButton *)sender {
    EditeAddressViewController *editViewController = [[EditeAddressViewController alloc] init];
    editViewController.isEdit = NO;
    if (!self.addresss || [self.addresss count] == 0) {
        editViewController.mustApprove = YES;
    }
    [self.navigationController pushViewController:editViewController animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}

- (void)approveAddress:(UIButton *)btn label:(UILabel *)label {
    if (btn.isSelected) {
        [btn setSelected:NO];
        label.textColor = [UIColor blackColor];
    }else {
        [btn setSelected:YES];
        label.textColor = kAppThemeColor;
    }
}

#pragma mark 编辑按钮
- (void)editAddress:(Address *)address {
    EditeAddressViewController *editViewController = [[EditeAddressViewController alloc] init];
    editViewController.address = address;
    editViewController.isEdit = YES;
    [self.navigationController pushViewController:editViewController animated:YES];
}

#pragma mark 删除地址
- (void)deleteAddress:(Address *)address{
    __weak typeof (self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定要删除该地址吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
        hud.mode = MBProgressHUDModeIndeterminate;
        [UpdateNet deleteAddress:address.addrNo completer:^(id resultObject, NSError *error) {
            hud.mode = MBProgressHUDModeText;
            if(error) {
                hud.label.text = [error localizedDescription];
                [hud hideAnimated:YES afterDelay:2];
            }
        }];
        [weakSelf.addresss removeObject:address];
        if ([address.isApprove isEqualToString:@"是"]) {
            Address *addr = [weakSelf.addresss firstObject];
            addr.isApprove = @"是";
        }
        [weakSelf.tableView reloadData];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

// 默认地址按钮
- (void)approveAddress:(UIButton *)btn label:(UILabel *)label address:(Address *)address {
    if(btn.isSelected) {
        return;
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    NSDictionary *dic = @{@"addrNo":address.addrNo, @"linkName":address.name, @"userAddr":address.provice, @"userAddr2":address.city, @"userAddr3":address.area, @"userAddr4":address.detail, @"phoneNumber":address.tel, @"defaultAddr": @"是"};
    [UpdateNet updateAddress:dic completer:^(id resultObject, NSError *error) {
        hud.mode = MBProgressHUDModeText;
        if(error) {
            hud.label.text = [error localizedDescription];
            [hud hideAnimated:YES afterDelay:2];
            return;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:UPDATEADDRESSNOTIFICATION object:resultObject];
        [hud hideAnimated:YES];
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
